// pages/personDetail/personDetail.js
import { updateStudent } from '../../api/person'

const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Page({
  data: {
    studentInfo: {},
    defaultAvatarUrl: defaultAvatarUrl,
    genderOptions: ['男', '女'],
    genderIndex: 0,
    educationOptions: ['本科', '硕士', '博士', '专科'],
    educationIndex: 0,
    isSaving: false
  },

  onLoad(options) {
    this.loadStudentInfo();
  },

  onShow() {
    this.loadStudentInfo();
  },

  // 从本地存储加载学生信息
  loadStudentInfo() {
    const studentInfo = wx.getStorageSync('studentInfo');
    if (studentInfo) {
      // 设置默认值
      const updatedInfo = {
        ...studentInfo,
        birthday: studentInfo.birthday || '',
        className: studentInfo.className || '',
        education: studentInfo.education || '',
        enrollmentDate: studentInfo.enrollmentDate || studentInfo.mercallTime || '',
        age: studentInfo.age || studentInfo.def || 0
      };
      
      // 设置选择器索引
      const genderIndex = studentInfo.gender === '女' ? 1 : 0;
      const educationIndex = this.data.educationOptions.indexOf(studentInfo.education);
      const finalEducationIndex = educationIndex !== -1 ? educationIndex : 0;
      
      this.setData({
        studentInfo: updatedInfo,
        genderIndex: genderIndex,
        educationIndex: finalEducationIndex
      });
    } else {
      // 如果没有登录信息，跳转到登录页
      wx.redirectTo({
        url: '/pages/logs/logs'
      });
    }
  },

  // 保存信息到服务器
  async saveInfo() {
    if (this.data.isSaving) return;
    const { studentInfo } = this.data;
    console.log('当前学生信息:', studentInfo);
    // 基本验证
    if (!studentInfo.studentName || !studentInfo.studentName.trim()) {
      wx.showToast({
        title: '请输入昵称',
        icon: 'none'
      });
      return;
    }

    if (!studentInfo.gender) {
      wx.showToast({
        title: '请选择性别',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({
      title: '保存中...',
    });

    this.setData({ isSaving: true });

    try {
      // 准备提交给后端的数据
      const submitData = {
        id: studentInfo.id,
        studentNo: studentInfo.studentNo,
        avatar:studentInfo.avatar,
        studentName: studentInfo.studentName.trim(),
        gender: studentInfo.gender,
        age: studentInfo.age || 0,
        classId: studentInfo.classId || 3,
        majorDictId: studentInfo.majorDictId || studentInfo.mapforDictId || 1,
        gradeDictId: studentInfo.gradeDictId || 1,
        education: studentInfo.education || '',
        phone: studentInfo.phone || '',
        enrollTime: studentInfo.enrollmentDate || studentInfo.mercallTime || '',
        status: studentInfo.status || 0,
        medicalHistory: studentInfo.medicalHistory || '无',
        psychologicalHistory: studentInfo.psychologicalHistory || '无',
        familySituation: studentInfo.familySituation || '正常',
        psychologicalTestResult: studentInfo.psychologicalTestResult || '正常'
      };
      console.log('提交到后端的数据:', submitData);

      // 调用更新学生信息接口
      const result = await updateStudent(submitData);
      
      wx.hideLoading();
      console.log(result);

      if (result) {
        // 更新本地存储的学生信息
        const updatedStudentInfo = {
          ...studentInfo,
          studentName: submitData.studentName,
          gender: submitData.gender,
          age: submitData.age,
          education: submitData.education,
          enrollmentDate: submitData.enrollTime
        };
        
        wx.setStorageSync('studentInfo', updatedStudentInfo);
        
        wx.showToast({
          title: '保存成功',
          icon: 'success',
          duration: 1500
        });

        // 返回上一页
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      } else {
        wx.showToast({
          title: result.msg || '保存失败',
          icon: 'none',
          duration: 2000
        });
      }
    } catch (error) {
      console.error('保存学生信息失败:', error);
      wx.hideLoading();
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none',
        duration: 2000
      });
    } finally {
      this.setData({ isSaving: false });
    }
  },

  // 更换头像
  changeAvatar() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0];
        this.setData({
          'studentInfo.avatar': tempFilePath
        });
        
        // 这里可以添加上传到服务器的逻辑
        wx.showToast({
          title: '头像已更新',
          icon: 'success'
        });
      }
    });
  },

  // 表单输入处理
  onNicknameInput(e) {
    this.setData({
      'studentInfo.studentName': e.detail.value
    });
  },

  onGenderChange(e) {
    const index = e.detail.value;
    this.setData({
      genderIndex: index,
      'studentInfo.gender': this.data.genderOptions[index]
    });
  },

  onBirthdayChange(e) {
    this.setData({
      'studentInfo.birthday': e.detail.value
    });
  },

  onClassInput(e) {
    this.setData({
      'studentInfo.className': e.detail.value
    });
  },

  onEducationChange(e) {
    const index = e.detail.value;
    this.setData({
      educationIndex: index,
      'studentInfo.education': this.data.educationOptions[index]
    });
  },

  onEnrollmentChange(e) {
    this.setData({
      'studentInfo.enrollmentDate': e.detail.value
    });
  },

  // 年龄输入处理（如果需要）
  onAgeInput(e) {
    this.setData({
      'studentInfo.age': parseInt(e.detail.value) || 0
    });
  }
})